package com.movisol.messengerprofileservice.asynctasks;

import java.util.List;

import android.os.AsyncTask;
import android.widget.Toast;

import com.movisol.messengerprofileservice.controllers.ProfileController;
import com.movisol.messengerprofileservice.data.UserProfile;
import com.movisol.messengerprofileservice.exceptions.ProfileServiceWebFault;
import com.movisol.messengerprofileservice.helpers.MessengerProfileHelper;
import com.movisol.messengerprofileservice.interfaces.errorcodes.SaveUserProfileErrorCodes;
import com.movisol.tools.HelperUtils;

public class AsyncSaveUserProfile extends AsyncTask<Void, Void, String>{
	
	private ProfileController pc = ProfileController.getInstance();

	@Override
	protected String doInBackground(Void... params) {
		
		return pc.saveUserProfile(pc.getTmpUserProfile());
	}

	/* (non-Javadoc)
	 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
	 */
	@Override
	protected void onPostExecute(String result) {
		super.onPostExecute(result);
		
		
		if(result != null)
		{
			List<Object> list = MessengerProfileHelper.parseXMLprofileToObject(result);
			
			if(list.get(0) != null)
			{
				pc.setUserProfile((UserProfile)list.get(0));		
				pc.fireUserProfileDataLoadedEvent(null);
//				HelperUtils.showToastMessage(pc.getContext(),"Profile Updated", Toast.LENGTH_SHORT);
				
			}
			
			if(list.get(1) != null)
			{
				String error = SaveUserProfileErrorCodes.getErrorByCode(((ProfileServiceWebFault)list.get(1)).getIntegerErrorCode());
				
				pc.fireUserProfileDataLoadedEvent( error);
				HelperUtils.LogE(getClass(), error);
				HelperUtils.showToastMessage(pc.getContext(),error, Toast.LENGTH_SHORT);
			}
		}
		else
		{
			HelperUtils.LogE(getClass(), null);
			pc.fireUserProfileDataLoadedEvent(SaveUserProfileErrorCodes.getErrorByCode(SaveUserProfileErrorCodes.INTERNAL_ERROR));
		}
	}
	
	
}
